package com.d3works.apps.bankpayment.web;

import com.d3works.apps.bankpayment.db.BankOrderLineOrigin;
import com.d3works.apps.bankpayment.exception.BankPaymentExceptionMessage;
import com.d3works.apps.bankpayment.service.bankorder.BankOrderLineOriginService;
import com.d3works.dms.db.DMSFile;
import com.d3works.exception.service.TraceBackService;
import com.d3works.i18n.I18n;
import com.d3works.inject.Beans;
import com.d3works.meta.schema.actions.ActionView;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import java.util.Map;

public class BankOrderLineOriginController {

  public void showDMSFiles(ActionRequest request, ActionResponse response) {

    BankOrderLineOrigin bankOrderLineOrigin =
        request.getContext().asType(BankOrderLineOrigin.class);
    Map<String, Object> relatedDataMap =
        Beans.get(BankOrderLineOriginService.class).getRelatedDataMap(bankOrderLineOrigin);

    response.setView(
        ActionView.define(I18n.get("Files"))
            .model(DMSFile.class.getName())
            .add("grid", "dms-file-grid")
            .add("form", "dms-file-form")
            .domain(
                "self.relatedModel = :relatedModel AND self.relatedId = :relatedId AND self.isDirectory = false")
            .context("relatedModel", relatedDataMap.get("relatedModel"))
            .context("relatedId", relatedDataMap.get("relatedId"))
            .context("_showSingle", true)
            .map());

    if (request.getContext().get("_source") != null) {
      response.setCanClose(true);
    }
  }

  public void displayDmsFileButton(ActionRequest request, ActionResponse response) {
    try {
      BankOrderLineOrigin bankOrderLineOrigin =
          request.getContext().asType(BankOrderLineOrigin.class);
      if (!Beans.get(BankOrderLineOriginService.class).dmsFilePresent(bankOrderLineOrigin)) {
        response.setAttr("displayInvoiceBtn", "hidden", true);
      }
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }

  public void alertNoDmsFile(ActionRequest request, ActionResponse response) {
    try {
      BankOrderLineOrigin bankOrderLineOrigin =
          request.getContext().asType(BankOrderLineOrigin.class);
      if (!Beans.get(BankOrderLineOriginService.class).dmsFilePresent(bankOrderLineOrigin)) {
        response.setError(I18n.get(BankPaymentExceptionMessage.BANK_ORDER_LINE_ORIGIN_NO_DMS_FILE));
      }
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }
}
